<?php
/**
 * Created by PhpStorm.
 * User: yxb
 * Date: 2016/12/23
 * Time: 16:28
 */
namespace app\index\controller;
use think\Db;
use think\Controller;
use think\Url;
class Car extends Controller{
    /**
    购物车
     * @param uid
     * @param assess_token
     */
    public function shopping_car($uid = 0,$assess_token = ''){
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $where = [
                's.is_delete' => 0,
                'g.is_delete' => 0,
                'g.status' => 1,
                's.uid' => $uid
            ];
            $join = [
                ['goods g','g.id=s.g_id','left']
            ];
            $field = [
                'g.subject',
                'g.introduction',
                'g.cover',
                's.ids',
                's.num',
                's.price',
                's.integral',
                's.id',
                's.g_id'
            ];
            $carts = Db::name("shopping_cart")->alias('s')->where($where)->join($join)->field($field)->order('s.timestamp desc')->select();
            foreach($carts as $key => $value){
                $ids = explode(',',$value['ids']);
                $yan = Db::name("properties_color")->where(array('id'=>$ids[0]))->where(array('is_delete'=>0))->find();
//                $idss = [];
                for($i=1;$i<count($ids);$i++){
                    $idss[] = $ids[$i];
                }
//                dump($idss);die;
                $feiyan = Db::name("propertise")->where('id','in',$idss)->where('is_delete',0)->select();
//                dump($feiyan);die;
                $c = array();
                for($j=0;$j<count($feiyan);$j++) {
                    $c[] = $feiyan[$j]['properties_name'];
                }
                $zifu = implode('/',$c);
                $carts[$key]['assessment'] =  $yan['properties_name'].'/'.$zifu;
            }
            if(empty($carts)){
                $carts = "";
            }
            return format_return(1,$carts,"数据获取成功");
        }
    }
    /**
    加入购物车，商品详情页
     * @param uid
     * @param assess_token
     * @param g_id 商品id
     * @param ids 属性
     */
    public function add_car($uid = 0,$assess_token = '',$g_id = 0,$ids = '',$num = 0){
        empty($g_id) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $where_car = [
                'is_delete' => 0,
                'uid' => $uid,
                'g_id' => $g_id,
                'ids' => $ids
            ];
            $car = Db::name("shopping_cart")->where($where_car)->find();
            if(!empty($car)){
                $update = [
                    'num' => $num+$car['num']
                ];
                $res = Db::name("shopping_cart")->where($where_car)->update($update);
            }else{
                $ids = explode(',',$ids);
                $where = [
                    'is_delete' => 0,
                    'id' => $ids[0]
                ];
                $goods = Db::name('properties_color')->where($where)->find();
//                $good = Db::name('propertise')->where($where)->group('classify_name')->select();
                $zong = 0;
                for($i=1;$i<count($ids);$i++){
                    $c[] = $ids[$i];
                    $d = Db::name('propertise')->where(array('id'=>$ids[$i]))->find();
                    $zong = $d['properties_price']+$zong;
                }
                $str_ids = implode(',',$ids);
                $zong = $zong+$goods['properties_price'];
                $goods = Db::name("goods")->where('id',$g_id)->where('status',1)->where('is_delete',0)->find();
                if(!empty($goods)){
                    $data = [
                        'uid' => $uid,
                        'g_id' => $g_id,
                        'ids' => $str_ids,
                        'num' => $num,
                        'price' => $zong,
                        'integral' => $goods['integral'],
                        'timestamp' => time()
                    ];
                    $res = Db::name("shopping_cart")->insertGetId($data);
                }else{
                    return format_return(0,'',"商品已下架");
                }

            }
            if(!empty($res)){
                return format_return(1,'',"添加成功");
            }else{
                return format_return(0,'',"添加失败");
            }
        }
    }
    /**
    商品列表页添加购物车
     * @param uid
     * @param assess_token
     * @param g_id 商品id
     * @param num
     */
    public function add_car_list($uid = 0,$assess_token = '',$g_id = 0){
        empty($g_id) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $good1 = Db::name("goods")->where('id',$g_id)->where('status',1)->where('is_delete',0)->find();
            if(empty($good1)){
                return format_return(0,'',"商品已下架");
            }
            $where = [
                'is_delete' => 0,
                'goods_id' => $g_id
            ];
//            $goods_assessment = Db::name("goods_assessment")->where($where)->select();
//            $sa = array_column($goods_assessment,'atr_id');
//            $sa = array_unique($sa);
//            foreach($sa as $key => $value){
//                for($i = 0; $i < sizeof($goods_assessment); $i ++){
//                    if($value == $goods_assessment[$i]['atr_id']){
//                        $assess[] = $goods_assessment[$i];
//                        break;
//                    }
//                }
//            }
//            $p = Db::name('goods')->where(array('id'=>$g_id))->find();
            $goods = Db::name('properties_color')->where($where)->find();
            $good = Db::name('propertise')->where($where)->group('classify_name')->select();
            $zong = 0;
            for($i=0;$i<count($good);$i++){
                $c[] = $good[$i]['id'];
                $zong = $good[$i]['properties_price']+$zong;
            }
            $zifu = implode(',',$c);
            $str_ids =  $goods['id'].','.$zifu;
            $zong = $zong+$goods['properties_price'];
            $where_car = [
                'is_delete' => 0,
                'uid' => $uid,
                'g_id' => $g_id,
                'ids' => $str_ids
            ];
            $car = Db::name("shopping_cart")->where($where_car)->find();
            if(!empty($car)){
                $car['num']++;
                $res = Db::name("shopping_cart")->where($where_car)->update(['num'=>$car['num']]);
            }else{
                $data = [
                    'uid' => $uid,
                    'g_id' => $g_id,
                    'ids' => $str_ids,
                    'num' => 1,
                    'price' => $zong,
                    'integral' =>$good1['integral'] ,
                    'timestamp' => time()
                ];
                $res = Db::name("shopping_cart")->insertGetId($data);
            }
            if(!empty($res)){
                return format_return(1,'',"添加成功");
            }else{
                return format_return(0,'',"添加失败");
            }
        }
    }
        /**
        购物车修改
         *  @param uid
         * @param assess_token
         * @param s_id 购物车id
         * @param ids 商品属性
         */
    public function update_car($uid = 0,$assess_token = '',$s_id = 0,$ids = ''){
        empty($s_id) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            Db::name("shopping_car")->where('id',$s_id)->update(['ids'=>$ids]);
            return format_return(1,'',"修改成功");
        }
    }
    /**
    删除购物车
     * @param uid
     * @param assess_token
     * @param id 购物车id
     */
    public function delete_car($uid = 0,$assess_token = '',$id = 0){
        empty($id) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $ids = explode(',',$id);
            $res = Db::name("shopping_cart")->where('id','in',$ids)->update(['is_delete'=> 1]);
            if(!empty($res)){
                return format_return(1,'',"删除成功");
            }else{
                return format_return(0,'',"删除失败");
            }
        }
    }
    /**
    购物车加减
     * @param uid
     * @param assess_token
     * @param id 购物车id
     * @param type 0加1减
     * @param num 数量
     */
    public function algorithm($uid = 0,$assess_token = '',$id = 0, $type = 0,$num = 0){
        empty($id) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $car =  Db::name("shopping_cart")->where('id',$id)->find();
            $where_goods = [
                'is_delete' => 0,
                'id' => $car['g_id']
            ];
            $goods = Db::name("goods")->where('id',$where_goods)->find();
            if(empty($goods)){
                return format_return(0,'',"商品删除");
            }else{
                if($type == 0){
                    $num++;
                    $car['price'] += $goods['price'];
                    $car['integral'] += $goods['integral'];
                }else{
                    $num--;
                    $car['price'] -= $goods['price'];
                    $car['integral'] -= $goods['integral'];
                }
                $data = [
                    'num' => $num,
                    'price' => $car['price'],
                    'integral' => $car['integral']
                ];
                if($num <= 0){
                    Db::name("shopping_cart")->where('id',$id)->update(['is_delete'=>1]);
                    return format_return(1,'',"成功");
                }else{
                    Db::name("shopping_cart")->where('id',$id)->update($data);
                    unset($car);
                    $car = Db::name("shopping_cart")->where('id',$id)->find();
                    return format_return(1,$car,"成功");
                }
            }
        }
    }

    /**
    购物车提交订单
     * @param uid
     * @param assess_token
     * @param ids 购物车ids
     */
    public function add_order($uid = 0,$assess_token = '',$ids = ''){
        empty($ids) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $res_ii = 1;
            while($res_ii == 1){
                $order_num = str_pad(str_replace('.', '', microtime(true)), 14, 0);
                $ress = Db::name("orders")->where("order_num",$order_num)->find();
                if(empty($ress)){
                    $res_ii ++;
                }
            }
            $ids1 = explode(',',$ids);
            $where = [
                'is_delete' => 0
            ];
            $where['id'] = array('in',$ids1);
            $carts = Db::name("shopping_cart")->where($where)->select();
            $integral = array_sum(array_column($carts,"integral"));
            $member = Db::name("members")->where('uid',$uid)->find();
            if($member['integral'] < $integral || $member['status_type'] == 0){
                return format_return(0,'',"积分不够，提交订单失败");
            }
//            $where_address = [
//                'is_delete' => 0,
//                'uid' => $uid,
//                'is_sure' => 1
//            ];
//            $address = Db::name("address")->where($where_address)->find();
//            if(empty($address)){
//                unset($where_address['is_sure']);
//                $address = Db::name("address")->where($where_address)->find();
//            }
            for($i = 0; $i < sizeof($carts); $i++){
                $where_goods = [
                    'status' => 1,
                    'is_delete' => 0,
                    'id' => $carts[$i]['g_id']
                ];
                $test_goods = Db::name("goods")->where($where_goods)->find();
                if(empty($test_goods)){
                    return format_return(0,'','商品已下架');
                }
                $data[$i]['order_id'] = str_pad(str_replace('.', '', microtime(true)), 14, 0)+$i;
                $data[$i]['ids'] = $ids;
                $data[$i]['uid'] = $uid;
                $data[$i]['car_id'] = $carts[$i]['id'];
                $data[$i]['is_car'] = 1;
                $data[$i]['price'] = $carts[$i]['price']*$carts[$i]['num'];
                $data[$i]['integral'] = $carts[$i]['integral']*$carts[$i]['num'];
                $data[$i]['nums'] = $carts[$i]['num'];
                $data[$i]['order_num'] = $order_num;
                $data[$i]['create_timestamp'] = time();
                $data[$i]['g_id'] = $carts[$i]['g_id'];
                $goods_cart = Db::name("goods")->where("id",$carts[$i]["g_id"])->find();
                $data[$i]['m_id'] = $goods_cart['m_id'];
                $data[$i]['mc_id'] = $goods_cart['mc_id'];
                $data[$i]['s_id'] = $goods_cart['s_id'];
//                if(!empty($address)){
//                    $data[$i]['address'] = $address['id'];
//                }
            }
            $res = Db::name("orders")->insertAll($data);
            Db::name("shopping_cart")->where('id','in',$ids)->update(['is_delete'=>1]);
            if(!empty($res)){
                return format_return(1,$order_num,"提交成功");
            }else{
                return format_return(0,'',"提交失败");
            }
        }
    }
    /**
    购物车订单页面
     * @param uid
     * @param assess_token
     * @param order_num 合并订单号
     */
    public function order($uid = 0,$assess_token = '',$order_num = ''){
        empty($order_num) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $where = [
                'uid' => $uid,
                'is_delete' => 0,
                'is_cancel' => 0,
                'status' => 0,
                'order_num' => $order_num
            ];
            $field = [
                'g_id',
                'order_id',
                'order_num',
                'price',
                'integral',
                'ids',
                'nums',
                'address'
            ];
            $orders = Db::name("orders")->where($where)->field($field)->select();
            $where_address = [
                'is_delete' => 0,
                'id' => $orders[0]['address']
            ];
            $address = Db::name("address")->where($where_address)->find();
            $g_ids = array_column($orders,'g_id');
            $where_goods = [
                'is_delete' => 0,
                'id' => array('in',$g_ids),
                'status' => 1
            ];
            $field_goods = [
                'id',
                'subject',
                'cover',
                'introduction',
                'price',
                'integral'
            ];
            $goods = Db::name("goods")->where($where_goods)->field($field_goods)->select();
            if(empty($goods)){
                return format_return(0,'','商品已下架');
            }
            $all_price = 0;
            $all_integral = 0;
            foreach($orders as $key => $value){
                $ids = explode(',',$value['ids']);
                $orders[$key]['attribute'] = Db::name("goods_assessment")->where('id','in',$ids)->where('is_delete',0)->select();
                $all_price += $value['price'];
                $all_integral += $value['integral'];
            }
            for($j = 0; $j <sizeof($orders); $j++){
                $orders[$j]['goods'] = '';
            }
            for($i = 0; $i < sizeof($goods); $i++){
                for($j = 0; $j <sizeof($orders); $j++){
                    if($goods[$i]['id'] == $orders[$j]['g_id']){
                        $orders[$j]['goods'] = $goods[$i];
                    }
                }
            }
            $data['address'] = $address;
            $data['order'] = $orders;
            $data['all_price'] = $all_price;
            $data['all_integral'] = $all_integral;
            return format_return(1,$data,"数据获取成功");
        }
    }

    /**
    修改支付方式
     * @param uid
     * @param assess_token
     * @param order_num 合并订单号
     * @param trading_type 交易方式 0微信1支付宝
     */
    public function update_trading_type($uid = 0,$assess_token = '',$order_num = '',$trading_type = 0){
        empty($order_num) && $this->error("非法参数");
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            $where = [
                'order_num' => $order_num,
                'uid' => $uid,
                'is_cancel' => 0,
                'status' => 0
            ];
            Db::name("orders")->where($where)->update(['trading_type'=>$trading_type]);
            return format_return(1,'',"修改成功");
        }
    }

    /**
    购物车数量
     * @param uid
     * @param assess_token
     * @param car_ids
     * @param nums
     */
    public function car_num($uid = 0,$assess_token = '',$car_ids = '',$nums = ''){
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else{
            if(!empty($car_ids) && !empty($nums)){
                $ids = explode(',',$car_ids);
                $num = explode(',',$nums);
                for($i = 0; $i < sizeof($ids); $i ++ ){
                    $data = [
                        'num' => $num[$i],
                    ];
                    Db::name("shopping_cart")->where('id',$ids[$i])->update($data);
                }
            }
            return format_return(1,'',"修改成功");
        }
    }

}